package flowshop.testCases;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Fetch {

	private String _siteName;
	private String _htmlFileName;

	public Fetch() {
		_siteName = new String(
				"http://mistic.heig-vd.ch/taillard/problemes.dir/ordonnancement.dir/");
		_htmlFileName = new String("ordonnancement.html");
	}

	public List<String> getFilesNames(String url) throws MalformedURLException,
			IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader((new URL(
				url)).openStream()));

		String line;
		ArrayList<String> list = new ArrayList<String>();

		Pattern pattern = Pattern.compile("flowshop.dir/tai[0-9]*_[0-9]*.txt");
		while ((line = bf.readLine()) != null) {
			Matcher matcher = pattern.matcher(line);
			if (matcher.find()) {
				list.add(matcher.group());
			}
		}
		bf.close();
		return list;
	}

	public List<String> downloadFile(String url) throws MalformedURLException,
			IOException {

		List<String> linesList = new ArrayList<String>();

		BufferedReader bf = new BufferedReader(new InputStreamReader((new URL(
				url)).openStream()));
		String line;
		while ((line = bf.readLine()) != null) {
			linesList.add(line);
		}

		bf.close();
		return linesList;
	}

	public List<String> parseTextToFile(List<String> fileText)
			throws UnrecognizedFileException {
		ArrayList<String> list = new ArrayList<String>();

		String[] stringList = new String[4];

		if (!fileText
				.get(0)
				.equals("number of jobs, number of machines, initial seed, upper bound and lower bound :")) {
			throw new UnrecognizedFileException();
		}

		if (!fileText.get(2).equals("processing times :")) {
			throw new UnrecognizedFileException();
		}

		stringList = fileText.get(1).split("[\\s]+");

		list.add(stringList[1] + " " + stringList[2] + " " + stringList[4]
				+ " " + stringList[5]);

		list.addAll(fileText.subList(3, fileText.size()));

		return list;
	}

	public void saveToFile(List<String> textToSave, String fileName)
			throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));

		for (String line : textToSave) {
			bw.write(line);
			bw.newLine();
		}

		bw.close();
	}

	public List<List<String>> divideIntoLists(List<String> fileText) {
		List<List<String>> listOfLists = new ArrayList<List<String>>();
		int index = 0;

		for (String s : fileText) {
			if (s.equals("number of jobs, number of machines, initial seed, upper bound and lower bound :")) {
				listOfLists.add(new ArrayList<String>());
				index = listOfLists.size() - 1;
				listOfLists.get(index).add(s);
			} else {
				listOfLists.get(index).add(s);
			}
		}

		return listOfLists;
	}

	public void run() throws MalformedURLException, IOException,
			UnrecognizedFileException {
		List<String> listOfFiles;

		listOfFiles = getFilesNames(_siteName + _htmlFileName);

		for (String file : listOfFiles) {
			List<String> fileText = downloadFile(_siteName + file);
			List<List<String>> listOfLists = divideIntoLists(fileText);
			int i = 1;
			Pattern pattern = Pattern.compile("tai[0-9]*_[0-9]*");
			Matcher matcher = pattern.matcher(file);
			String actualFileName = null;
			if (matcher.find()) {
				actualFileName = matcher.group();
			}
			System.out.println((new StringBuffer())
					.append(System.getProperty("user.dir"))
					.append("/testCases/").append(actualFileName).append("_")
					.append(i).append(".txt").toString());
			for (List<String> testCase : listOfLists) {
				List<String> textToSave = parseTextToFile(testCase);
				saveToFile(
						textToSave,
						(new StringBuffer())
								.append(System.getProperty("user.dir"))
								.append("/testCases/").append(actualFileName)
								.append("_").append(i).append(".txt")
								.toString());
				i++;
			}

		}
	}

	public void setSiteName(String _siteName) {
		this._siteName = _siteName;
	}

	public void setHTMLFileName(String _htmlFileName) {
		this._htmlFileName = _htmlFileName;
	}

	public static void main(String[] args) throws IOException,
			UnrecognizedFileException {

		Fetch f = new Fetch();

		f.run();
	}
}
